//
//  Common.m
//  GoldOperationClient
//
//  Created by yaxue wang on 16/8/4.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "Common.h"
#import <QiniuSDK.h>
#import "GTMBase64.h"
#include <CommonCrypto/CommonCrypto.h>
#import <AFNetworking.h>

@interface Common()
{
    NSString *_name;
}

@end
#define SYSTEM_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]
#define IS_IOS7 (SYSTEM_VERSION >= 7.0 && SYSTEM_VERSION < 8.0)

@implementation Common
+ (void)makePhoneWith:(NSString*)string
{
    //2、调用 电话phone
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",string];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}
+ (void)setSearchBarStyle:(UISearchBar *)searchBar
{
    searchBar.backgroundImage = [UIColor imageWithString:@"#ffffff" size:CGSizeMake(SCREEN_WIDTH, 44)];
    
    UITextField *textField = [Common getSearchBarTextField:searchBar];
    if (textField) {
//        textField.layer.borderColor = [UIColor  colorFromHexString:@"#f1f1f1"].CGColor;
//        textField.layer.borderWidth = 1;
//        textField.layer.cornerRadius = textField.frame.size.width/2;
//        textField.layer.masksToBounds = YES;
    }
}
+ (UITextField *)getSearchBarTextField:(UISearchBar *)searchBar
{
    UITextField *textField = nil;
    if (IS_IOS7) {
        for (UIView *view in searchBar.subviews) {
            for (UIView *subView in view.subviews) {
                if ([subView isKindOfClass:[UITextField class]]) {
                    textField = (UITextField *)subView;
                    break;
                }
            }
        }
    } else {
        for (UIView *subView in searchBar.subviews) {
            if ([subView isKindOfClass:[UITextField class]]) {
                textField = (UITextField *)subView;
                break;
            }
        }
    }
    return textField;
}
//计算自适应高度
+ (CGFloat)getLabelHeight:(CGFloat)height Width:(CGFloat)width String:(NSString *)str
{
    //    高度随便写，尽量写大一点
    CGSize size = CGSizeMake(width, 1000);
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:[UIFont systemFontOfSize:height] forKey:NSFontAttributeName];
    CGRect frame = [str boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return frame.size.height;
}
+(CGRect)computeRect:(NSString *)text Font:(NSInteger)fontSize{
 
    NSDictionary *dic = [NSDictionary dictionaryWithObject:F(fontSize) forKey:NSFontAttributeName];
    CGRect rect = [text boundingRectWithSize:CGSizeMake(2000, 300) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect;
}

//检测是否是手机号码
//+ (BOOL)isMobileNumber:(NSString *)mobileNum
//{
//    //    NSString * MOBILE = @"^1\\d{10}$";
//    NSString * MOBILE =@"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
//    //
//    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES%@", MOBILE];
//    
//    return [regextestmobile evaluateWithObject:mobileNum];
// 
//}
+ (NSString *)getDateTimeString
{
    NSDateFormatter *formatter;
    NSString        *dateString;
    
    formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd_HH:mm:ss"];
    
    dateString = [formatter stringFromDate:[NSDate date]];
    
    return dateString;
}


+ (NSString *)randomStringWithLength:(int)len
{
    NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
    
    for (int i=0; i<len; i++) {
        [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random_uniform((int)[letters length])]];
    }
    
    return randomString;
}

//创建文件夹
+ (void)createDirectoryWith:(NSString *)path
{
    //createDirectoryAtPath创建一个文件夹，第一个参数是创建的文件夹的路径，第二个参数是是否自动创建路径中不存在的文件夹。
    [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
}
////七牛上传凭证
//+ (NSString *)makeToken:(NSString *)accessKey secretKey:(NSString *)secretKey type:(NSString*)type
//{
//    const char *secretKeyStr = [secretKey UTF8String];
//    
//    NSString *policy = [Common marshalWithType:type];
//    
//    NSData *policyData = [policy dataUsingEncoding:NSUTF8StringEncoding];
//    
//    NSString *encodedPolicy = [GTMBase64 stringByWebSafeEncodingData:policyData padded:TRUE];
//    const char *encodedPolicyStr = [encodedPolicy cStringUsingEncoding:NSUTF8StringEncoding];
//    
//    char digestStr[CC_SHA1_DIGEST_LENGTH];
//    bzero(digestStr, 0);
//    
//    CCHmac(kCCHmacAlgSHA1, secretKeyStr, strlen(secretKeyStr), encodedPolicyStr, strlen(encodedPolicyStr), digestStr);
//    
//    NSString *encodedDigest = [GTMBase64 stringByWebSafeEncodingBytes:digestStr length:CC_SHA1_DIGEST_LENGTH padded:TRUE];
//    
//    NSString *token = [NSString stringWithFormat:@"%@:%@:%@",  accessKey, encodedDigest, encodedPolicy];
//    
//    return token;//得到了token
//}

//+ (NSString *)marshalWithType:(NSString*)type
//{
//    time_t deadline;
//    time(&deadline);//返回当前系统时间
//    int expires;
//    deadline += (expires > 0) ? expires : 3600; // +3600秒,即默认token保存1小时.
//    
//    NSNumber *deadlineNumber = [NSNumber numberWithLongLong:deadline];
//    
//    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//    NSString *string =[NSString stringWithFormat:@"kingop-test:%@",[Common createFileName:type]] ;
//    [dic setObject:string forKey:@"scope"];//根据
//    [dic setObject:deadlineNumber forKey:@"deadline"];
//    
//    NSString *json =[Common dictionaryToJson:dic];
//    
//    return json;
//}
+(void)uploadDataWithData:(NSData*)data type:(NSString*)type

{
    NSString *AK =@"5sczmEmyO7d-_pou0kR2UOPL3gKY_J9nZTtsCIWY";
    NSString *SK = @"1xalhtp2_-h0nxr0mqzRCxadBpTT8Qybl4NJbdb9";
    NSString *token = [self makeToken:AK secretKey:SK type:type];
//    NSDictionary *dic = @{@"hhh":@"aaa",@"test":@"memei"};
    
//   NSString *str  =[Common dictionaryToJson:dic];
//    
//    NSString *str =[Common dictionaryToJson:dic];
//    NSData *data =[str dataUsingEncoding:NSUTF8StringEncoding]; ;//转为JSON格式，便于下载
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    [upManager putData:data key:[Common marshalWithType:type] token:token
              complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                  
                  echo(([NSString stringWithFormat:@"info = %@\n", info]));
                  echo(([NSString stringWithFormat:@"key = %@\n",key]));
                  echo(([NSString stringWithFormat:@"resp = %@\n", resp]));

              } option:nil];
}




//上传
//+ (void)uploadImageToQNFilePath:(NSString *)filePath withMine:(NSString*)type {
//    NSString *AK =@"5sczmEmyO7d-_pou0kR2UOPL3gKY_J9nZTtsCIWY";
//    NSString *SK = @"1xalhtp2_-h0nxr0mqzRCxadBpTT8Qybl4NJbdb9";
//    NSString *token = [self makeToken:AK secretKey:SK];
////    NSData *data =[filePath JSONData];//转为JSON格式，便于下载
//    
//    
//    QNUploadManager *upManager = [[QNUploadManager alloc] init];
//    QNUploadOption *uploadOption = [[QNUploadOption alloc] initWithMime:type progressHandler:^(NSString *key, float percent) {
//        NSLog(@"percent == %.2f", percent);
//    }
//                                                                 params:nil
//                                                               checkCrc:NO
//                                                     cancellationSignal:nil];
//    [upManager putFile:filePath key:nil token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
//        NSLog(@"info ===== %@", info);
//        
//        NSLog(@"resp ===== %@", resp);
//    }
//                option:uploadOption];
//}
//17位随机数
+(NSString *)createFileName:(NSString *)suff{
    int rand1 = arc4random() % 1000000 + 1000000;
    int rand2 = arc4random() % 10000 + 10000;
    int rand3 = arc4random() % 10000 + 10000;
    return [NSString stringWithFormat:@"%d%d%d%@", rand1, rand2, rand3, suff];
}
/*!
* @brief 把格式化的JSON格式的字符串转换成字典

* @param jsonString JSON格式的字符串

* @return 返回字典

*/

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        
        return nil;
    
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                         
                                                        options:NSJSONReadingMutableContainers
                         
                                                          error:&err];
    
    if(err) {
//        NSLog(@"json解析失败：%@",err);
        
        return nil;
        
    }
    
    return dic;
    
}

+ (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
@end
